package com.quanyan.ic.protocol.client.handler;

import com.quanyan.ic.protocol.MessageType;
import com.quanyan.ic.protocol.codec.protobuf.ICMessageProto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.ScheduledFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhuo.shi on 2017/5/31.
 */
public class HeartBeatReqHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(HeartBeatReqHandler.class);

    private volatile ScheduledFuture<?> heartBeat;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ICMessageProto.ICMessage message = (ICMessageProto.ICMessage) msg;
        if (message.getHeader() != null && message.getHeader().getType() == MessageType.HANDSHAKE_RESP.value()) {
            logger.info("send HeartBeat msg to server at fixed rate");
            heartBeat = ctx.executor().scheduleAtFixedRate(
                    new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS);

        } else if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
            if (logger.isDebugEnabled()) {
                logger.debug("receive server heart beat resp message: ---> " + message);
            }
        } else {
            ctx.fireChannelRead(message);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (heartBeat != null) {
            heartBeat.cancel(true);
            heartBeat = null;
        }
        ctx.fireExceptionCaught(cause);
    }

    private class HeartBeatTask implements Runnable {
        private final ChannelHandlerContext ctx;

        public HeartBeatTask(final ChannelHandlerContext ctx) {
            this.ctx = ctx;
        }

        @Override
        public void run() {
            ICMessageProto.ICMessage heatBeat = buildHeatBeat();
            logger.debug("Client send heart beat message to server :-->" + heatBeat);
            ctx.writeAndFlush(heatBeat);
        }

        private ICMessageProto.ICMessage buildHeatBeat() {
            ICMessageProto.ICMessage.Builder builder = ICMessageProto.ICMessage.newBuilder();
            ICMessageProto.ICMessage.Header.Builder hbuilder = ICMessageProto.ICMessage.Header.newBuilder();
            hbuilder.setProtocolVersion(0xAF1);
            hbuilder.setType(MessageType.HEARTBEAT_REQ.value());
            hbuilder.setPid(34080);
            builder.setHeader(hbuilder.build());
            return builder.build();
        }
    }
}
